package com.gjy.rocketmq.product;

import com.gjy.rocketmq.RocketUtil;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2023-01-29 09:48:37
 */
public class OrderlyProduct {

    private static final Logger logger = LoggerFactory.getLogger(OrderlyProduct.class);

    public static void main(String[] args) throws Exception {

        DefaultMQProducer producer = new DefaultMQProducer(RocketUtil.ProducerGroup);
        producer.setNamesrvAddr(RocketUtil.NAME_SRV);
        producer.start();

        String[] tags = {"A", "B", "C", "D", "E"};
        for (int i = 0; i < 100; i++) {
            int orderId = i % 10;
            int nextInt = ThreadLocalRandom.current().nextInt(5);
            Message message = new Message(RocketUtil.TOPIC_TEST, tags[nextInt], "KEY" + i,
                    ("hello " + i).getBytes(StandardCharsets.UTF_8));
            SendResult result = producer.send(message, (mqs, msg, arg) -> {
                Integer id = (Integer) arg;
                int index = id % mqs.size();
                return mqs.get(index);
            }, orderId);
            logger.info("{}", result);
        }
        TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
        producer.shutdown();
    }
}
